// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// t [author] rhyme_lph
// Y [email]  rhymelph@gmail.com
// N [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:extended_nested_scroll_view/extended_nested_scroll_view.dart';
import 'package:finance_app/generated/a.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/common/app_colors.dart';
import 'package:finance_app/src/common/app_spaces.dart';
import 'package:finance_app/src/entities/dashboard_entity.dart';
import 'package:finance_app/src/page/dashboard/dashboard_overview_view.dart';
import 'package:finance_app/src/page/dashboard/dashboard_transactions_view.dart';
import 'package:finance_app/src/provider/dashboard/dashboard_view_provider.dart';
import 'package:finance_app/src/provider/dashboard_provider.dart';
import 'package:finance_app/src/widgets/button/balance_choose_button.dart';
import 'package:finance_app/src/widgets/button/normal_float_svg_button.dart';
import 'package:finance_app/src/widgets/common_tab_bar.dart';
import 'package:finance_app/src/widgets/tablet_padding.dart';
import 'package:flutter/material.dart' hide NestedScrollView;
import 'package:tuple/tuple.dart';

import 'dashboard_contacts_view.dart';

class DashboardView extends StatefulWidget {
  @override
  _DashboardViewState createState() => _DashboardViewState();
}

class _DashboardViewState extends State<DashboardView>
    with
        StatefulPresenter<DashboardView, DashboardProvider,
            DashboardViewProvider>,
        KeepAliveMixin {
  @override
  Widget buildWidget(BuildContext context) => ColoredBox(
        color: Colors.white,
        child: listBuilder<bool>(
          selector: (_, __) => __.buttonBarIsUp,
          builder: (BuildContext context, bool value, Widget child) => Stack(
            children: [
              child,
              // _buildTop(),
              _buildBottomButton(value),
              // _buildTop(),
            ],
          ),
          child: _buildRecordList(),
        ),
      );

  Widget _buildRecordList() {
    return DefaultTabController(
      length: provider.tabList.length,
      child: Builder(
        builder: (BuildContext context) => NestedScrollView(
          controller: provider.controller,
          headerSliverBuilder: _buildSliverHeader,
          pinnedHeaderSliverHeightBuilder: () => 48.0,
          innerScrollPositionKeyBuilder: () {
            return Key("Tab${DefaultTabController.of(context).index}");
          },
          body: TabletPadding(
            child: Column(
              children: [
                Expanded(child: TabBarView(children: _buildTabView())),
              ],
            ),
          ),
        ),
      ),
    );
  }

  Widget _buildBalance() => ColoredBox(
        color: Colors.white,
        child: Column(
          children: [
            SizedBox(
              height: getDp(20),
            ),
            listBuilder<DashboardEntity>(
                builder: (BuildContext context, DashboardEntity value,
                    Widget child) {
                  return BalanceChooseButton(
                    title: S.current.cash_balance,
                    number: value.balance,
                    onTap: provider.onNavCashBalance,
                    numberColor: aceBlackColor,
                    borderColor: aceGrayColor,
                  );
                },
                selector: (_, __) => __.data),
            AppSpaces.h10,
            listBuilder<Tuple2<String, String>>(
                builder: (BuildContext context, Tuple2<String, String> value,
                        Widget child) =>
                    BalanceChooseButton(
                      title: S.current.unpaid_invoice,
                      number: value.item1,
                      overdueNumber:
                          value.item2.contains(' 0.00') ? null : value.item2,
                      onTap: provider.onNavUnpaidInvoice,
                      numberColor: aceGreenColor,
                      borderColor: aceGreenColor.withOpacity(0.28),
                    ),
                selector: (_, __) => Tuple2(
                    __.data.unpaidInvoice, __.data.unpaidInvoiceOverdue)),
            AppSpaces.h10,
            listBuilder<Tuple2<String, String>>(
                builder: (BuildContext context, Tuple2<String, String> value,
                        Widget child) =>
                    BalanceChooseButton(
                      title: S.current.unpaid_bill,
                      number: value.item1,
                      overdueNumber:
                          value.item2.contains(' 0.00') ? null : value.item2,
                      onTap: provider.onNavUnPaidBill,
                      numberColor: aceRedColor,
                      borderColor: aceRedColor.withOpacity(0.28),
                    ),
                selector: (_, __) =>
                    Tuple2(__.data.unpaidBill, __.data.unpaidBillOverdue)),
            AppSpaces.h20,
          ],
        ),
      );

  Widget _buildTabBar() => CommonTabBar(
        key: provider.tabBarKey,
        tabs: provider.tabList
            .map((e) => MyTab(
                  text: provider.getTabTitle(e),
                ))
            .toList(),
      );

  Widget _buildBottomButton(bool isTop) => AnimatedPositioned(
      duration: Duration(milliseconds: 300),
      left: 0.0,
      right: 0.0,
      bottom: isTop
          ? MediaQuery.of(context).padding.bottom + getDp(40)
          : -getDp(60),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          NormalFloatSvgButton(
            key: provider.ocrCameraKey,
            onTap: provider.onNavCamera,
            asset: A.assetsImagesDashboardPhoto,
          ),
          AppSpaces.w35,
          NormalFloatSvgButton(
            key: provider.transactionKey,
            onTap: provider.onNavAdd,
            asset: A.assetsImagesDashboardAdd,
          ),
        ],
      ));

  _buildTabView() {
    return [
      NestedScrollViewInnerScrollPositionKeyWidget(
          Key("Tab0"), DashboardOverviewView()),
      NestedScrollViewInnerScrollPositionKeyWidget(
          Key("Tab1"), DashboardTransactionsView()),
      NestedScrollViewInnerScrollPositionKeyWidget(
          Key("Tab2"), DashboardContactsView()),
    ];
  }

  List<Widget> _buildSliverHeader(
      BuildContext context, bool innerBoxIsScrolled) {
    return <Widget>[
      SliverToBoxAdapter(
        child: TabletPadding(child: _buildBalance()),
      ),
      SliverToBoxAdapter(
        child: TabletPadding(child: _buildTabBar()),
      ),
    ];
  }
}

class SliverHeader extends SliverPersistentHeaderDelegate {
  final double maxExtent;
  final double minExtent;
  final Widget child;

  SliverHeader({this.maxExtent, this.minExtent, this.child});

  @override
  Widget build(
      BuildContext context, double shrinkOffset, bool overlapsContent) {
    return ColoredBox(
        color: Theme.of(context).scaffoldBackgroundColor, child: child);
  }

  @override
  bool shouldRebuild(covariant SliverPersistentHeaderDelegate oldDelegate) {
    return false;
  }
}
